package online.lona.mc.bukkit.plugin.ymer;

import online.lona.mc.NativeInterface;
import online.lona.mc.YmerPlayer;
import online.lona.mc.bukkit.plugin.ymer.event.YmerAuthStartEvent;
import org.bukkit.entity.Player;

public class ModCheckTask implements Runnable {
    private final String playerName;
    private final YmerPlayer ymerPlayer;
    private boolean isCancelled;

    public ModCheckTask(String playerName, YmerPlayer ymerPlayer) {
        this.playerName = playerName;
        this.ymerPlayer = ymerPlayer;
        isCancelled = false;
    }

    @Override
    public void run() {
        if (isCancelled) {
            return;
        }
        final Player player = Ymer.plugin.getServer().getPlayer(playerName);
        if (player != null && player.isOnline()) {
            ModCheckTask task = new ModCheckTask(playerName, ymerPlayer);
            YmerAuthStartEvent event = new YmerAuthStartEvent(Ymer.Ymer, Ymer.Ymer.getServer().getPlayer(playerName));
            Ymer.Ymer.getServer().getPluginManager().callEvent(event);
            if (event.isCancelled()) {
                Ymer.plugin.getServer().getScheduler().runTaskLater(Ymer.plugin, task, Config.getInstance().getAuthInterval() * 20);
                Ymer.Ymer.taskMap.put(playerName, task);
            } else {
                NativeInterface.getInstance().VerClient(ymerPlayer);
                Ymer.plugin.getServer().getScheduler().runTaskLater(Ymer.plugin, new Runnable() {
                    @Override
                    public void run() {
                        if (!Ymer.Ymer.getPlayerCheckStatus(playerName)) {
                            if (isCancelled) {
                                return;
                            }
                            if (player.isOnline()) {
                                ymerPlayer.onFileAuthenticationTimeout();
                            }
                        } else {
                            Ymer.plugin.getServer().getScheduler().runTaskLater(Ymer.plugin, task, Config.getInstance().getAuthInterval() * 20);
                            Ymer.Ymer.taskMap.put(playerName, task);
                        }
                    }
                }, Config.getInstance().getAuthTimeout() * 20);
            }
        }
    }

    public void setCancelled(boolean cancelled) {
        isCancelled = cancelled;
    }
}
